package com.tieshu.matissecrop;


import android.Manifest;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.tieshu.matissecrop.utils.DisplayUtil;
import com.tieshu.matissecrop.utils.GlideCircleBorderTransform;
import com.tieshu.matissecrop.utils.MyGlideEngine;
import com.tieshu.matissecrop.utils.PicCrop;
import com.yalantis.ucrop.UCrop;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

public class MainActivity extends AppCompatActivity {
    private Button button;
    private ImageView imageView;
    private static final int CAMERA_PERMISSIONS_REQUEST_CODE = 0x03;
    private static final int STORAGE_PERMISSIONS_REQUEST_CODE = 0x04;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = findViewById(R.id.button);
        imageView = findViewById(R.id.imageView);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                autoObtainStoragePermission();
            }
        });
    }

    private void autoObtainStoragePermission() {

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {


            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, CAMERA_PERMISSIONS_REQUEST_CODE);
        }else {

            openMatisse();
        }

    }

    public void openMatisse() {

        PicCrop.cropFromMatisse(PicCrop.TYPE_AVATAR);
        Matisse.from(MainActivity.this)
                .choose(MimeType.of(MimeType.JPEG, MimeType.PNG, MimeType.GIF))//照片视频全部显示MimeType.allOf()
                .countable(true)//true:选中后显示数字;false:选中后显示对号
                .maxSelectable(1)//最大选择数量为9
                //.addFilter(new GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
                .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))//图片显示表格的大小
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)//图像选择和预览活动所需的方向
                .thumbnailScale(0.85f)//缩放比例
                .theme(R.style.Matisse_Zhihu)//主题  暗色主题 R.style.Matisse_Dracula
                .imageEngine(new MyGlideEngine())//图片加载方式，Glide4需要自定义实现
                .capture(true) //是否提供拍照功能，兼容7.0系统需要下面的配置

                //参数1 true表示拍照存储在共有目录，false表示存储在私有目录；参数2与 AndroidManifest中authorities值相同，用于适配7.0系统 必须设置
                .captureStrategy(new CaptureStrategy(false, "com.tieshu.matissecrop.FileProvider"))//存储到哪里
                .forResult(PicCrop.REQUEST_SELECT_PICTURE);//请求码
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        switch (requestCode) {


            case CAMERA_PERMISSIONS_REQUEST_CODE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    openMatisse();
                } else {
                    Toast.makeText(MainActivity.this, "请允许打操作SDCard！！", Toast.LENGTH_LONG).show();
                }
                break;
            default:
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        PicCrop.onActivityResult(requestCode, resultCode, data, this, cropHandler);
    }

    /**
     * 自动获取sdk权限
     */
    private PicCrop.CropHandler cropHandler = new PicCrop.CropHandler() {
        @Override
        public void handleCropResult(Uri data, int tag) {


            if (data != null) {
                RequestOptions myOptions;
                myOptions = new RequestOptions()
                        .placeholder(R.mipmap.ic_launcher)
                        .optionalTransform
                                (new GlideCircleBorderTransform(DisplayUtil.dip2px(MainActivity.this, 2), getResources().getColor(R.color.white)));


                Glide.with(MainActivity.this).load(data).apply(myOptions).into(imageView);
            }
        }

        @Override
        public void handleCropError(Intent data) {
            final Throwable cropError = UCrop.getError(data);
            Log.e("AAAA",cropError.getMessage());
            Toast.makeText(MainActivity.this, cropError.getMessage(), Toast.LENGTH_LONG).show();

        }
    };
}